import {
	ref,
} from 'vue'
import config from '@/utils/config.js';
const toastRef = ref(null)
const showToast = (message, type = 'default') => {
	toastRef.value?.show({
		type,
		message
	})
}

const api_root = config.baseUrl
let api = {
	// #ifndef H5
	auth_app_id: uni.getAccountInfoSync().miniProgram.appId, // 小程序 appId
	// #endif
	// #ifdef H5
	auth_app_id: "2024092317069911", // 小程序 appId
	// #endif
	shop_id: "1",
	admin_id: "10001"
};

let requestList = [] // 登录失效时未请求成功的集合
let timer = null; // 节流控制定时器
/**
 * 封装请求方法
 * @param {Object} options - 请求配置项
 * @param {Function} success - 请求成功回调
 * @param {Function} fail - 请求失败回调
 */
function request(options, success, fail) {
	// // #ifndef H5
	// const url = api_root + '/data/' + options.url;
	// // #endif
	// // #ifdef H5
	// const url = '/api/data/' + options.url
	// // #endif
	const url = api_root + '/data/' + options.url
	// 判断请求方法
	const method = options.method || "GET";
	// 构造请求数据
	const data = buildParams(options.data || {});
	// 构造请求头
	const headers = getRequestHeader(method, options.headers || {});
	uni.request({
		url,
		method,
		data,
		header: headers,
		headers,
		dataType: "json",
		success: (res) => {
			const {
				statusCode,
				data,
			} = res
			if (statusCode === 200) {
				if (data.code === 0 || data.code === -1) {
					handleErrorResponse(options, success, fail, data, statusCode);
				} else {
					success && success(data.data);
				}
			} else {
				handleErrorResponse(options, success, fail, data, statusCode);
			}
		},
		fail: (error) => {
			const {
				statusCode,
				data,
			} = error
			console.log(error);
			handleErrorResponse(options, success, fail, data, statusCode);
		},
	});
};

function uploadFile(url) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: api_root + '/data/' + 'miniprogram.upload/state',
			filePath: url,
			fileType: "image",
			name: 'file',
			formData: {
				safe: 0,
				uptype: "alioss"
			},
			success: (res) => {
				const data = JSON.parse(res.data).data.upload
				resolve(data)
			}
		});
	})

}
// 重新发送失败的请求
function retryFailedRequests() {
	requestList.forEach(({
		options,
		success,
		fail
	}, index) => {
		requestList.splice(index, 1)
		request(options, success, fail);
	})
}

// 错误响应处理
function handleErrorResponse(options, success, fail, data, statusCode) {
	// 重试队列管理
	requestList.push({
		options,
		success,
		fail
	});
	if (data.code == -1) {
		// 登录失效后的处理及重试
		//#ifndef H5
		doLogin(retryFailedRequests);
		// #endif

		// #ifdef H5
		h5overdue(retryFailedRequests)
		// #endif
	} else {
		showError(data?.info, retryFailedRequests, fail, statusCode);
	}
}
/**
 * 构造请求参数
 * @param {Object} data - 额外请求参数
 * @returns {Object} 合并后的请求参数
 */
function buildParams(data) {
	return Object.assign({}, api, data);
}
/**
 * 设置请求头header
 * @param {string} method - HTTP请求方法
 * @param {Object} [headers] - 自定义请求头
 * @returns {Object} 合并后的完整请求头
 */
function getRequestHeader(method, headers = {}) {
	let userInfo = uni.getStorageSync("userInfo");
	let token = userInfo && userInfo.token && userInfo.token.token ? userInfo.token.token : null; // token

	// 合并自定义请求头
	return Object.assign({
			"content-type": method == "GET" ? "application/json" : "application/x-www-form-urlencoded",
			// #ifdef MP-WEIXIN
			"Api-Type": "wxapp",
			// #endif
			// #ifdef H5
			"Api-Type": "wap",
			// #endif
			"api-token": token
		},
		headers
	);
}
/**
 * 判断是否需要验证登录
 */
function checkLogin(url, loading) {
	console.log(url, 'url')
	if (url == 'api.auth.center/getshopindex') {
		console.log('相等')
		return false
	}
	loading && uni.showLoading({
		title: '加载中',
		//mask: true
	});
	const check_login = url.includes('auth')
	const now = Math.round(new Date().getTime() / 1000);
	const expire = uni.getStorageSync("expire");
	return check_login && now >= expire
}
/**
 * Axios风格的请求封装（支持loading状态）
 * @param {{url: string, data?: object, method?: string, loading?: boolean}} config - 请求配置
 * @returns {Promise<any>} 返回一个Promise用于处理异步结果
 */
async function axios({
	url,
	data,
	method,
	loading = true
}) {
	// #ifndef H5
	const check_login = await checkLogin(url, loading)
	// #endif
	return new Promise((resolve, reject) => {
		const success = (res) => {
			resolve(res)
			hideLoading()
		}
		const fail = (res) => {
			reject(res)
			hideLoading()
		}
		const hideLoading = () => {
			timer = null
			loading && setTimeout(() => {
				uni.hideLoading();
			}, 100);
		}
		const PromiseRequest = () => {
			request({
				url,
				data,
				method,
			}, success, fail);
		};
		// PromiseRequest()
		// 判断是否需要验证登录
		// #ifndef H5
		check_login ? doLogin(PromiseRequest, fail) : PromiseRequest();
		// #endif
		// #ifdef H5
		PromiseRequest()
		// #endif
	})
}

// GET请求封装
function get(url, data = {}, loading) {
	return axios({
		url,
		data,
		loading
	});
}

// POST请求封装
function post(url, data = {}, loading) {
	return axios({
		url,
		data,
		method: "POST",
		loading
	});
}

function h5overdue(callback) {
	// uni.clearStorageSync()
	uni.showModal({
		content: "当前登录已失效,请先登录",
		confirmText: "去登陆",
		cancelText: "取消",
		success: (res) => {
			if (res.confirm) {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
		}
	});
}

/**
 * 执行登录操作
 * @param {Function} callback - 登录成功后执行的回调函数
 * @param {Function} fail - 登录失败或授权码获取失败后的回调函数
 */
function doLogin(callback, fail) {
	console.log("doLogin")
	const login = code => {
		// const url = getUrlType()
		post("api.Wechatapp/login", {
			code,
			// from: "0"
		}).then(res => {
			if (res) {
				token = res.token.token
				uni.setStorageSync("expire", res.token.expire);
				uni.setStorageSync("userInfo", res);
			}
			// 执行回调函数
			callback && callback();
			timer = null
		}, ).catch((err) => {
			fail && fail();
			timer = null
		});
	};
	// 节流
	if (!timer) {
		timer = +new Date()
		getAuthCode(login, fail);
	}
}
/**
 * 获取授权码
 * @param {Function} callback - 成功后回调
 * @param {Function} fail - 失败后回调
 */
function getAuthCode(callback, fail) {
	console.log('getAuthCode')
	const app = getApp()
	if (app.globalData.loginList.some(p => p == app.globalData.appType)) {
		uni?.login({
			force: true,
			success(res) {
				console.log(res);
				res && callback && callback(res?.code);
			},
			fail(res) {
				getAuthCodeError(fail)
			},
			complete() {
				uni.hideLoading();
			}
		});
	} else {
		fail && fail()
		uni.hideLoading()
		uni.showModal({
			content: "您还没有登录,请先登录",
			confirmText: "去登陆",
			cancelText: "取消",
			success: (res) => {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			}
		});
	}
}
/**
 * 授权码获取失败处理
 * @param {Function} fail - 失败后回调
 */
function getAuthCodeError(fail) {
	uni.navigateBack()
	uni.showModal({
		title: '温馨提示',
		content: "获取授权码失败",
		confirmText: "我知道了",
		showCancel: false,
		success: res => {
			timer = null
			fail && fail()
		}
	});
}


// function getUrlType() {
// 	const app = getApp();
// 	const appType = app.globalData.appType
// 	console.log(appType);
// 	let data = 'dyapp'
// 	switch (appType) {
// 		case 'mp-weixin':
// 			data = 'wxapp'
// 			break;
// 		case 'mp-toutiao':
// 			data = 'dyapp'
// 			break;
// 		default:
// 			data = 'dyapp'
// 			break;
// 	}
// 	return data
// }
let num = 0;
// 显示失败提示框
function showError(msg, callback, fail, statusCode) {
	uni.hideLoading();
	uni.showModal({
		title: "友情提示",
		content: msg || "当前网络异常，请稍后刷新重试或联系平台客服！" + '(' + statusCode + ')',
		confirmText: "重试",
		cancelText: "我知道了",
		success: (res) => {
			if (res.cancel) {
				num = 0;
				requestList = [];
				fail && fail();
			} else if (num >= 2) {
				callPhone(fail, statusCode)
			} else if (res.confirm) {
				num += 1;
				callback && callback();
			}
		}
	});
}

function callPhone(fail, statusCode) {
	const app = getApp()
	uni.showModal({
		title: "友情提示",
		content: "当前网络异常，请稍后刷新重试或联系平台客服！" + '(' + statusCode + ')',
		confirmText: "联系平台客服",
		cancelText: "我知道了",
		success: (res) => {
			if (res.confirm) {
				app.callPhone()
			}
			num = 0;
			requestList = [];
			fail && fail();
		}
	});
}
export {
	api_root,
	get,
	post,
	axios,
	request,
	uploadFile,
	getAuthCode,
	doLogin
}